package repostiory

import (
	"context"
	"gitee.com/chicken-c/go-learn/webook/internal/domain"
	"gitee.com/chicken-c/go-learn/webook/internal/repostiory/cache"
)

type RankingRepostiory interface {
	ReplaceTopN(ctx context.Context, arts []domain.Article) error
	GetTopN(ctx context.Context) ([]domain.Article, error)
}

type CachedRankingRepostiory struct {
	localCache *cache.LocalRankingCache
	redisCache *cache.RedisRankingCache
}

func (c *CachedRankingRepostiory) GetTopN(ctx context.Context) ([]domain.Article, error) {
	arts, err := c.localCache.Get(ctx)
	if err == nil {
		return arts, nil
	}

	arts, err = c.redisCache.Get(ctx)
	if err == nil {
		//回写到本地缓存
		_ = c.localCache.Set(ctx, arts)
	} else {
		//一个兜底的策略，当redis崩溃了，我们从本地缓存中加载已经过期的数据
		arts, _ = c.localCache.ForceGet(ctx)
	}
	return arts, nil
}

func NewCachedRankingRepostiory(localCache *cache.LocalRankingCache, redisCache *cache.RedisRankingCache) RankingRepostiory {
	return &CachedRankingRepostiory{localCache: localCache, redisCache: redisCache}
}

func (c *CachedRankingRepostiory) ReplaceTopN(ctx context.Context, arts []domain.Article) error {
	_ = c.localCache.Set(ctx, arts)
	return c.redisCache.Set(ctx, arts)
}
